<?php

namespace app\common\business;

use app\common\model\mysql\SGoods as SGoodsModel;
use app\common\model\mysql\SGoodsCategory;

class SGoods
{
    public $goodsObj = null;
    public $goodsCategoryObj = null;
    public function __construct()
    {
        $this->goodsObj = new SGoodsModel();
        $this->goodsCategoryObj = new SGoodsCategory();
    }

    /**
     * 查询商品列表
     * @param $where
     * @param $field
     * @param $limit
     * @param $page
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function getNormalGoodsData($where,$field,$limit,$page){
        $dictData = $this->goodsObj->getNormalGoodsList($where,$field,$limit,$page);
        if(!$dictData){
            return [];
        }
        $dictData = $dictData->toArray();
        return $dictData;
    }

    public function getNormalGoodsFieldData($where,$field){
        $dictData = $this->goodsCategoryObj->getNormalGoodsFieldList($where,$field);
        if(!$dictData){
            return [];
        }
        return $dictData;
    }

    //添加商品
    public function addGoods($data){
        try {
            $this->goodsObj->save($data);
        }catch (\Exception $e){
            throw new \think\Exception($e->getMessage());
        }
        return $this->goodsObj->id;
    }

    //根据$id,去数据库查询是否存在这条记录
    public function getGoodsById($id,$field = '*'){
        $user = $this->goodsObj->getGoodsByIdFind($id,$field);
        if(!$user){
            return [];
        }
        return $user->toArray();
    }

    /**
     * 根据主键id更新数据表中的数据
     * @param $id
     * @param $data
     * @return bool
     */
    public function updateById($id,$data){
        $id = intval($id);
        if(empty($id) || empty($data) || !is_array($data)){
            return false;
        }
        $where = [
            "goods_id"=>$id,
        ];
        return $this->goodsObj->where($where)->find()->save($data);
    }

    //根据$ids数组，删除数据库记录delete
    public function delGoodsIds($ids){
        $ids = explode(',', $ids);
        $result = $this->goodsObj->DelGoodsIds($ids);
        return $result;
    }

    //查询商品总条数
    public function getNormalGoodsCount($where){
        $postCount = $this->goodsObj->getNormalGoodsCount($where);
        if(!$postCount){
            return 0;
        }
        return $postCount;
    }

    /**
     * 根据主键id更新商品状态
     * @param $id
     * @param $data
     * @return bool
     */
    public function changeStatusGoods($goodsId,$status){
        $goodsId = intval($goodsId);
        if(empty($goodsId)){
            return false;
        }
        //根据$goodsId去数据库查询这条记录
        /*$postNameResult = $this->getUserById($goodsId);
        if($postNameResult){
            if($postNameResult['user_name'] == "admin"){
                throw new \think\Exception("不允许操作超级管理员用户");
            }
        }*/
        return $this->goodsObj->changeStatusGoodsModel($goodsId,$status);
    }
}
